package com.coolgor.coldot.common.database;

import com.coolgor.coldot.exceptions.database.C3p0OperationException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;

@Component
public class C3p0Util {

    private static Logger log = LoggerFactory.getLogger(C3p0Util.class);

//    //通过标识名来创建相应连接池
//    static ComboPooledDataSource dataSource=new ComboPooledDataSource("mysql");
    // 依赖注入连接池
    @Autowired
    static ComboPooledDataSource dataSource;

    //从连接池中取用一个连接
    public static Connection getConnection(){
        try {
//            return dataSource.getConnection();
            return dataSource.getConnectionPoolDataSource().getPooledConnection().getConnection();
        } catch (Exception e) {
            log.error("Exception in C3p0Utils!", e);
            throw new C3p0OperationException("数据库连接出错!" + e);
        }
    }


    //释放连接回连接池 Statement
    public static void close(Connection conn, Statement statement, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
    }


    //释放连接回连接池 PreparedStatement
    public static void close(Connection conn, PreparedStatement pst, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
        if(pst!=null){
            try {
                pst.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("Exception in C3p0Utils!", e);
                throw new C3p0OperationException("数据库连接出错!" + e);
            }
        }
    }
}